package ar.com.tallerdos.smartdinner.sync;

import java.util.List;

import ar.com.tallerdos.smartdinner.activity.SeleccionarMesasActivity;
import ar.com.tallerdos.smartdinner.business.MesaBusiness;
import ar.com.tallerdos.smartdinner.gson.serializer.MesaCustomSerializer;
import ar.com.tallerdos.smartdinner.model.Mesa;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class MesasAbiertasWSClient extends Tarea {
    private static final String MESAS_ABIERTAS_SERVICE = "consultarMesasDisponibles.php";

    private SeleccionarMesasActivity activity;
    private List<Mesa> mesas;

    public MesasAbiertasWSClient(SeleccionarMesasActivity mainActivity) {
	activity = mainActivity;
    }

    @Override
    public Integer realizarTarea() {
	String mesasJson = llamarWebService(SERVER_URL + "/" + MESAS_ABIERTAS_SERVICE);
	parsearMesas(mesasJson);
	
	for (Mesa mesa : mesas) {
	    MesaBusiness.createOrUpdate(mesa);
	}

	return null;
    }

    private void parsearMesas(String mesasJson) {
	Gson gson = new GsonBuilder().registerTypeAdapter(Mesa.class, new MesaCustomSerializer()).create();

	mesas = gson.fromJson(mesasJson,
		new TypeToken<List<Mesa>>() { }.getType()); 
    }

    @Override
    public void onPostExecute() {
        super.onPostExecute();
        activity.onFinishLoading();
    }
}
